let json = JSON(data: dataFromNetworking) iflet userName = json[0]["user"]["name"].string { //now you got your value }
并且你也不用担心可选类型拆包。这些都是自动帮你完成。
1 2 3 4 5 6 7
let json = JSON(data: dataFromNetworking) iflet userName = json[999999]["wrong_key"]["wrong_name"].string { //calm down, take it easy. the ".string" property still produces the current Optional String type with safety } else { //print the error print(json[999999]["wrong_ket"]["wrong_name"]) }
//从一个 JSON数组 里获取一个 字符串数组 let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue})
1 2
//从一个 JSON字典 中获取一个 string let name = json["name"].stringValue
1 2 3 4 5 6 7
//通过元素的路径来获取 string let path: [JSONSubscriptType] = [1, "list", 2, "name"] let name = json[path].string //同样的 let name = json[1]["list"][2]["name"].string //或者 let name = json[1, "list", 2, "name"].string
1 2
//条件苛刻的情况 let name = json[].string
1 2 3
//普通的方法 let keys: [SubscriptType] = [1, "list", 2, "name"] let name = json[keys].string
循环
1 2 3 4
//如果 JSON 是字典 for (key, subJson):(String, JSON) in json { //做你想做的事情 }
即使 JSON 是数组,第一个元素也总是字符串。
1 2 3 4 5
//如果 JSON是数组 //index 是0到JSON数量的一个字符串值 for (index, subJson):(String, JSON) in json { //做你想做的事情 }
错误
使用下标来获取或设置字典或数组里的一个值
如果 JSON 是:
一个数组,应用可能奔溃由于数组越界。
一个字典,它将返回 nil 并且没有原因。
不是字典或者数组,应用可能因为“不认识选择器”而奔溃。
这些在 SwiftyJSON 中都不会发生。
1 2 3 4 5 6
let json = JSON(["name", "age"]) iflet name = json[999].string { //做你想做的事情 } else { print(json[999].error)//"Array[999] 已经越界了" }
1 2 3 4 5 6
let json = JSON(["name":"Jack", "age": 25]) iflet name = json["address"].string { //做你想做的事情 } else { print(json["address"].error)//"Dictionary["address"]并不存在" }
let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] let json = JSON(dict) let representation = json.rawString(options: [.castNilToNSNull: true]) // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null}
和 Alamofire 一起使用
SWiftyJSON 很好地包装了 Alamofire JSON 相应的结果:
1 2 3 4 5 6 7 8 9 10
Alamofire.request(url, mothod: .get).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) print("JSON:\(json)") case .failure(let error): print(error) } }